<template>
  <div>
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="产品编号:">
        <el-input v-model="searchForm.ProductCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="产品名称:">
        <el-input v-model="searchForm.ProductName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="类型:">
        <el-select v-model="searchForm.CategoryId" placeholder="请选择产品类别">
          <el-option v-for="a in Category" :label="a.categoryName" :value="a.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getData()">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div style="margin: 10px 0;">
      <el-button type="primary" icon="el-icon-plus" @click="onAddProduct">新增</el-button>
      <!-- <el-button icon="el-icon-download" @click="handleExport">导出</el-button> -->
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="100" />
      <el-table-column prop="" type="index" label="序号" width="50" />
      <el-table-column prop="productCode" label="产品编号" width="100" />
      <el-table-column prop="productName" label="产品名称" width="180" />
      <el-table-column prop="manufacturerCode" label="厂商编号" width="100" />
      <el-table-column prop="internalCode" label="内部编号" width="100" />
      <el-table-column prop="specifications" label="规格" width="80" />
      <el-table-column prop="categoryName" label="类型" width="100" />
      <el-table-column prop="unitName" label="存储单位" width="100" />
      <el-table-column prop="earlyXia" label="预警(下)" width="100" />
      <el-table-column prop="earlyShang" label="预警(上)" width="100" />
      <el-table-column prop="packagingType" label="包装类型" width="100" />
      <el-table-column prop="price" label="价格" width="80" />
      <el-table-column prop="weight" label="重量" width="80" />
      <el-table-column prop="supplierName" label="默认供应商" width="120" />
      <el-table-column label="操作" width="120">
        <template #default="scope" style="">
          <el-button type="text" size="small" @click="ProductUpdate(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="ProductDelete(scope.row.productId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <table>
      <tbody>
        <tr>
          <td>
            <el-pagination v-model:current-page="searchForm.index" v-model:page-size="searchForm.size"
              :page-sizes="[15, 20, 30, 40]" :background="true" layout="slot, sizes" :total="searchForm.totalCount"
              prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
              共{{ searchForm.totalCount }}条 第{{ searchForm.index }}/{{ searchForm.totalPCount }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination v-model:current-page="searchForm.index" v-model:page-size="searchForm.size"
              :page-sizes="[15, 20, 30, 40]" :background="true" layout="slot, prev, pager, next"
              :total="searchForm.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange"
              @current-change="handleCurrentChange">
              <el-button size="small" @click="handleCurrentChange(1)" :disabled="searchForm.index == 1">首页</el-button>
            </el-pagination>
          </td>
          <td>
            <el-pagination v-model:current-page="searchForm.index" v-model:page-size="searchForm.size"
              :page-sizes="[15, 20, 30, 40]" :background="true" layout="slot, jumper" :total="searchForm.totalCount"
              prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
              <el-button size="small" @click="handleCurrentChange(searchForm.totalPCount)"
                :disabled="searchForm.index == searchForm.totalPCount">首页</el-button>
            </el-pagination>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- 添加 -->
    <el-dialog v-model="dialogTableVisible" title="添加" width="800">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" label-width="auto">
        <el-form-item label="产品编号" prop="productCode">
          <el-input v-model="ruleForm.productCode" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="ruleForm.productName" />
        </el-form-item>

        <el-form-item label="厂家编号" prop="manufacturerCode">
          <el-input v-model="ruleForm.manufacturerCode" />
        </el-form-item>

        <el-form-item label="内部编号" prop="internalCode">
          <el-input v-model="ruleForm.internalCode" />
        </el-form-item>
        <el-form-item label="单位" prop="unitId">
          <el-select v-model="ruleForm.unitId" placeholder="请选择单位">
            <el-option v-for="a in Unit" :label="a.unitName" :value="a.unitId" />
          </el-select>
        </el-form-item>

        <el-form-item label="类别" prop="categoryId">
          <el-select v-model="ruleForm.categoryId" placeholder="请选择类别">
            <el-option v-for="a in Category" :label="a.categoryName" :value="a.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="上限值" prop="earlyShang">
          <el-input v-model="ruleForm.earlyShang" />
        </el-form-item>
        <el-form-item label="下限值" prop="earlyXia">
          <el-input v-model="ruleForm.earlyXia" />
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="ruleForm.specifications" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="ruleForm.price" />
        </el-form-item>

        <el-form-item label="仓库" prop="depotId">
          <el-select v-model="ruleForm.depotId" placeholder="请选择仓库">
            <el-option v-for="a in Depot" :key="a.depotId" :label="a.depotName" :value="a.depotId" />
          </el-select>
        </el-form-item>

        <el-form-item label="库位" prop="locationId">
          <el-select v-model="ruleForm.locationId" placeholder="请选择库位">
            <el-option v-for="a in Location" :label="a.locationName" :value="a.locationId" />
          </el-select>
        </el-form-item>

        <el-form-item label="默认供应商" prop="supplierName">
          <el-input v-model="ruleForm.supplierName" />
        </el-form-item>

        <el-form-item label="客户" prop="clientId">
          <el-select v-model="ruleForm.clientId" placeholder="请选择客户">
            <el-option v-for="a in Client" :label="a.clientName" :value="a.clientId" />
          </el-select>
        </el-form-item>

        <el-form-item label="包装类型" prop="packagingType">
          <el-input v-model="ruleForm.packagingType" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="ruleForm.weight" />
        </el-form-item>

        <el-form-item label="描述" prop="tel">
          <el-input v-model="ruleForm.categoryRemark" style="width: 240px" :rows="2" type="textarea" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            添加
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog v-model="dialogTableVisible1" title="修改" width="800">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" label-width="auto">
        <el-form-item label="产品编号" prop="productCode">
          <el-input v-model="ruleForm.productCode" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="ruleForm.productName" />
        </el-form-item>

        <el-form-item label="厂家编号" prop="manufacturerCode">
          <el-input v-model="ruleForm.manufacturerCode" />
        </el-form-item>

        <el-form-item label="内部编号" prop="internalCode">
          <el-input v-model="ruleForm.internalCode" />
        </el-form-item>
        <el-form-item label="单位" prop="unitId">
          <el-select v-model="ruleForm.unitId" placeholder="请选择单位">
            <el-option v-for="a in Unit" :label="a.unitName" :value="a.unitId" />
          </el-select>
        </el-form-item>

        <el-form-item label="类别" prop="categoryId">
          <el-select v-model="ruleForm.categoryId" placeholder="请选择类别">
            <el-option v-for="a in Category" :label="a.categoryName" :value="a.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="上限值" prop="earlyShang">
          <el-input v-model="ruleForm.earlyShang" />
        </el-form-item>
        <el-form-item label="下限值" prop="earlyXia">
          <el-input v-model="ruleForm.earlyXia" />
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="ruleForm.specifications" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="ruleForm.price" />
        </el-form-item>

        <el-form-item label="仓库" prop="depotId">
          <el-select v-model="ruleForm.depotId" placeholder="请选择仓库">
            <el-option v-for="a in Depot" :key="a.depotId" :label="a.depotName" :value="a.depotId" />
          </el-select>
        </el-form-item>

        <el-form-item label="库位" prop="locationId">
          <el-select v-model="ruleForm.locationId" placeholder="请选择库位">
            <el-option v-for="a in Location" :label="a.locationName" :value="a.locationId" />
          </el-select>
        </el-form-item>

        <el-form-item label="默认供应商" prop="supplierName">
          <el-input v-model="ruleForm.supplierName" />
        </el-form-item>

        <el-form-item label="客户" prop="clientId">
          <el-select v-model="ruleForm.clientId" placeholder="请选择客户">
            <el-option v-for="a in Client" :label="a.clientName" :value="a.clientId" />
          </el-select>
        </el-form-item>

        <el-form-item label="包装类型" prop="packagingType">
          <el-input v-model="ruleForm.packagingType" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="ruleForm.weight" />
        </el-form-item>

        <el-form-item label="描述" prop="tel">
          <el-input v-model="ruleForm.categoryRemark" style="width: 240px" :rows="2" type="textarea" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForms()">
            修改
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 引入Element Plus相关
import axios from 'axios'
import { ref, reactive, computed, onMounted } from 'vue'

// 筛选表单数据
const searchForm = reactive({
  ProductCode: '',
  ProductName: '',
  CategoryId: '',
  index: 1,
  size: 15,
  totalCount: 0,
  totalPCount: 0
})
// 表格数据（这里用静态数据，实际可用接口获取）
onMounted(() => {
  getData();
  getCategory();
  getUnit();
  getDepot();
  getLocation();
  getClient();
})
const tableData = ref([])
const getData = () => {
  http.get("/basicread/api/Product/GetProduct", { params: searchForm }).then(res => {
    tableData.value = res.data.data
    searchForm.totalCount = res.data.totalCount
    searchForm.totalPCount = res.data.totalPCount
  })
}
//重置
const handleReset = () => {
  searchForm.CategoryId = '',
    searchForm.ProductName = '',
    searchForm.ProductCode = ''
  getData()
}
//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  searchForm.size = val
  getData();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  searchForm.index = val
  getData();
}

const dialogTableVisible = ref(false)
const dialogTableVisible1 = ref(false)
//删除
import { ElMessageBox } from 'element-plus'

const ProductDelete = (productId: any) => {
  ElMessageBox.confirm(
    '确定删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      http.get("/basicwrite/api/Product/DelProduct?ProductId=" + productId).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          getData();
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除被取消',
      })
    })
}

//添加
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import http from '@/http/axiosHelper';

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "productId": 0,
  "productCode": "",
  "productName": "",
  "manufacturerCode": '',
  "internalCode": "",
  "specifications": "",
  "categoryId": '',
  "unitId": '',
  "earlyXia": '',
  "earlyShang": '',
  "packagingType": "",
  "price": "",
  "weight": "",
  "supplierName": "",
  "depotId": '',
  "locationId": '',
  "clientId": '',
  "categoryRemark": ""
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      http.post("/basicwrite/api/Product/AddProduct", ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          dialogTableVisible.value = false;

          ruleForm.productCode = '';
          ruleForm.productName = '';
          ruleForm.manufacturerCode = '';
          ruleForm.internalCode = '';
          ruleForm.specifications = '';
          ruleForm.categoryId = '';
          ruleForm.unitId = '';
          ruleForm.earlyXia = '';
          ruleForm.earlyShang = '';
          ruleForm.packagingType = '';
          ruleForm.price = '';
          ruleForm.weight = '';
          ruleForm.supplierName = '';
          ruleForm.depotId = '';
          ruleForm.locationId = '';
          ruleForm.clientId = '';
          ruleForm.categoryRemark = '';
          getData();
        }
        else {
          ElMessage.error(res.data.msg)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
const ProductUpdate=(row:any)=>{
  dialogTableVisible1.value=true;
  Object.assign(ruleForm,row)
}

const submitForms = () => {
    http.post("/basicwrite/api/Product/UpdateProduct",ruleForm).then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.msg);
      dialogTableVisible1.value = false;
          getData();
    }
    else
    {
      ElMessage.error(res.data.msg);
    }
    })
}


//类别下拉框
const Category = ref([{
  "categoryId": '',
  "categoryName": "",
}])
const getCategory = () => {
  http.get("/basicread/api/Category/GetCategory").then(res => {
    Category.value = res.data.data
  })
}
//单位下拉框
const Unit = ref([{
  "unitId": '',
  "unitName": "",
}])
const getUnit = () => {
  http.get("/basicread/api/Unit/GetUnit").then(res => {
    Unit.value = res.data.data
  })
}
//仓库
const Depot = ref([{
  "depotId": '',
  "depotName": "",
}])
const getDepot = () => {

  console.log(Depot.value);
  http.get("/basicread/api/Depot/GetDepot").then(res => {
    Depot.value = res.data.data
  })
}
//库位
const Location = ref([{
  "locationId": '',
  "locationName": "",
}])
const getLocation = () => {
  http.get("/basicread/api/Location/GetLocation").then(res => {
    Location.value = res.data.data
  })
}
//客户
const Client = ref([{
  "clientId": '',
  "clientName": "",
}])
const getClient = () => {
  http.get("/basicread/api/Client/GetClient").then(res => {
    Client.value = res.data.data
  })
}

function getNextProductCode() {
  if (!tableData.value.length) return 'CP001';
  // 提取所有编号中的数字部分
  const codes = tableData.value
    .map((item: any) => item.productCode)
    .filter((code: string) => /^CP\d{3}$/.test(code))
    .map((code: string) => parseInt(code.slice(2), 10));
  const max = codes.length ? Math.max(...codes) : 0;
  const next = (max + 1).toString().padStart(3, '0');
  return `CP${next}`;
}

function onAddProduct() {
  ruleForm.productCode = getNextProductCode();
  // 其余字段清空
  ruleForm.productName = '';
  ruleForm.manufacturerCode = '';
  ruleForm.internalCode = '';
  ruleForm.specifications = '';
  ruleForm.categoryId = '';
  ruleForm.unitId = '';
  ruleForm.earlyXia = '';
  ruleForm.earlyShang = '';
  ruleForm.packagingType = '';
  ruleForm.price = '';
  ruleForm.weight = '';
  ruleForm.supplierName = '';
  ruleForm.depotId = '';
  ruleForm.locationId = '';
  ruleForm.clientId = '';
  ruleForm.categoryRemark = '';
  dialogTableVisible.value = true;
}


// 多选相关
const multipleSelection = ref<any[]>([])
const hasSelection = computed(() => multipleSelection.value.length > 0)
function handleSelectionChange(val: any[]) {
  multipleSelection.value = val
}




</script>

<style scoped>
.filter-form {
  margin-bottom: 16px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
